/*
  学习目标：实现小智同学聊天-发送消息和接收消息
  步骤：

*/

import Icon from '@/components/Icon';
import Input from '@/components/Input';
import NavBar from '@/components/NavBar';
import { useEffect, useRef, useState } from 'react';
import styles from './index.module.scss';
import classNames from 'classnames';
import { io, Socket } from 'socket.io-client';
import { getAuth } from '@/utils/storage';

interface IMsg {
  type: 'robot' | 'user';
  msg: string;
  timestamp: number;
}

export default function Chat() {
  const [list, setList] = useState<IMsg[]>([]);
  const [msg, setMsg] = useState('');
  // 3. 创建ref 保存客户端实例
  const clientRef = useRef<Socket | null>(null);

  useEffect(() => {
    // 1. 创建ws的客户端实例
    clientRef.current = io('http://geek.itheima.net/', {
      query: {
        token: getAuth().token,
      },
      transports: ['websocket'],
    });

    // 2. 监听连接成功, 主动发送一条消息(欢迎语), 表示连接成功
    clientRef.current.on('connect', () => {
      setList([...list, { type: 'robot', msg: '有什么可以帮您', timestamp: Date.now() }]);
    });

    // 4. 监听消息, 渲染消息
    clientRef.current.on('message', (data) => {
      setList((preList) => {
        return [...preList, { ...data, type: 'robot' }];
      });
    });
    return () => {
      // 5.卸载时, 主动关闭
      clientRef.current?.close();
    };
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  const handleSendMsg = () => {
    const sendMsg = { msg, timestamp: Date.now() };
    setList([...list, { type: 'user', ...sendMsg }]);
    setMsg('');
    // 3. 发送消息
    clientRef.current?.emit('message', sendMsg);
  };

  useEffect(() => {
    window.scrollTo({ top: document.body.scrollHeight, behavior: 'smooth' });
  }, [list]);

  return (
    <div className={styles.root}>
      <NavBar fixed>小智同学</NavBar>

      <div className="chat-list">
        {list.map((item) => (
          <div className={classNames('chat-item', { user: item.type === 'user' })}>
            {item.type === 'user' ? (
              <img src={'http://toutiao.itheima.net/images/user_head.jpg'} alt="" />
            ) : (
              <Icon type="iconbtn_xiaozhitongxue" />
            )}
            <div className="message">{item.msg}</div>
          </div>
        ))}
      </div>

      <div className="footer">
        <div className="input-footer">
          <Input
            value={msg}
            onChange={(e) => setMsg(e.target.value)}
            className="no-border"
            placeholder="请描述您的问题"
          />
          <Icon type="iconbianji" />
          <span className="send" onClick={handleSendMsg}>
            发送
          </span>
        </div>
      </div>
    </div>
  );
}
